package service

import (
	"go-mall/conf"
	"go-mall/pkg/e"
	"go-mall/pkg/util"
	"go-mall/serializer"
	"io/ioutil"
	"mime/multipart"
	"os"
	"strconv"
)

type UploadService struct {
}

func UploadAvatarTOLocalStatic(file multipart.File, userId uint, productName string) (filePath string, err error) {
	bId := strconv.Itoa(int(userId))
	basePath := "." + conf.ProductPath + "boss" + bId + "/"
	if !DirExistOrNot(basePath) {
		CreateDir(basePath)
	}
	productPath := basePath + productName + ".jpg" // todo:把file的后缀提取出来
	content, err := ioutil.ReadAll(file)
	if err != nil {
		return "", err
	}
	err = ioutil.WriteFile(productPath, content, 0644)
	if err != nil {
		return
	}
	return "boss" + bId + "/" + productName + ".jpg", nil
}

func UploadProductToLocalStatic(file multipart.File, userId uint, userName string) (filePath string, err error) {
	bId := strconv.Itoa(int(userId)) //路径拼接
	basePath := "." + conf.AvatarPath + "user" + bId + "/"
	if !DirExistOrNot(basePath) {
		CreateDir(basePath)
	}
	avatarPath := basePath + userName + ".jpg" // todo:把file的后缀提取出来
	content, err := ioutil.ReadAll(file)
	if err != nil {
		return "", err
	}
	err = ioutil.WriteFile(avatarPath, content, 0644)
	if err != nil {
		return
	}
	return "user" + bId + "/" + userName + ".jpg", nil
}
func (service *UploadService) UploadImg(fileHeader *multipart.FileHeader) serializer.Response {
	code := e.Success
	// 打开上传的文件
	uploadedFile, err := fileHeader.Open()
	if err != nil {
		// 处理错误
		code = e.ErrorUploadFile
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	defer uploadedFile.Close()
	status, url := util.UploadToQiNiu(uploadedFile, fileHeader.Size)
	if status != 200 {
		// 处理错误
		code = e.ErrorUploadFile
		return serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
		}
	}
	return serializer.Response{
		Status: code,
		Msg:    e.GetMsg(code),
		Data:   url,
	}
}

// 判断文件夹路径是否存在
func DirExistOrNot(fileAddr string) bool {
	s, err := os.Stat(fileAddr)
	if err != nil {
		return false
	}
	return s.IsDir()
}

// CreateDir创建文件夹
func CreateDir(dirName string) bool {
	err := os.MkdirAll(dirName, 755)
	if err != nil {
		return false
	}
	return true
}
